﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PPIMobileInterface.Entities;
using PPIMobileInterface.Logic;
using PPIDesktopClient.Logic;
using PPIDesktopClient.Entities;
using System.IO;
using System.Configuration;
using VMind.Global;
using PPIDesktopClient.Entities.Xml;
using System.Collections;

namespace PPIDesktopClient.General
{
    public class UploadProcessImages : UploadProcess
    {
        protected int m_AmountDatabaseImages = 0;
        private Queue<EOutbox> m_QueueDatabases; 

        public EOutbox Database
        {
            get { return m_CurrentDatabase; }
            set { m_CurrentDatabase = value; }
        }

        public int TotalImages
        {
            get { return m_AmountDatabaseImages; }
        }

        public UploadProcessImages()
        {
            m_QueueDatabases = new Queue<EOutbox>();

        }
        public UploadProcessImages(EOutbox database)
        :this()
        {
            m_CurrentDatabase = database;

        }

        public override bool HasNextUpload()
        {
            return (m_QueueDatabases.Count > 0 || m_CurrentDatabase != null);
        }

        public void StartUpload(EOutbox database)
        {
            if (!m_UploaderWorker.IsBusy)
            {
                m_CurrentDatabase = database;
                if (database != null)
                {
                    RefreshValues();
                    OnUploadingNewDatabase(this, new EventArgs());
                    m_UploaderWorker.RunWorkerAsync();
                }
            }
            else
            {
                if (!m_QueueDatabases.Contains(database))
                    m_QueueDatabases.Enqueue(database);
            }
        }

        private void StartUploadQueue()
        {
            if (m_QueueDatabases.Count > 0)
            {
                m_CurrentDatabase = m_QueueDatabases.Dequeue();
                RefreshValues();
                OnUploadingNewDatabase(this, new EventArgs());
                m_UploaderWorker.RunWorkerAsync();
            }
            else
            {
                m_CurrentDatabase = null;
                OnUploaderCompleted(this, new EventArgs());
            }
            
            
        }

        public override void RefreshValues()
        {
            try
            {
                m_DatabaseConnectionString = m_CurrentDatabase.ConnectionString;
                m_DatabaseName = m_CurrentDatabase.Created.ToLongDateString();

                this.m_AmountDatabaseImages = LogicLayer.GetTotalImages(m_CurrentDatabase.ConnectionString);

            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        protected override void Upload(System.ComponentModel.DoWorkEventArgs e)
        {


            List<EImage> _MobileImages = LogicLayer.SelectImages(m_DatabaseConnectionString, false);
            List<EVendor_Visit_XMissionStructures_Image> m_ImagesUpload = LVendor_Visit_XMissionStructures_Image.GetImagesFromMobileImages(_MobileImages);
            m_TotalUpload = m_ImagesUpload.Count;

            Int32 _CountUploaded = m_TotalUpload;
            Int32 _ImageServerID;
            DirectoryInfo _ImagesDirectory = GetImagesDirectory();
            string _FullPathImage = "";

            try
            {
                foreach (EVendor_Visit_XMissionStructures_Image i in m_ImagesUpload)
                {
                    if (m_UploaderWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    _FullPathImage = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + i.FileName;
                    if (File.Exists(_FullPathImage))
                    {
                        i.FileName = i.Asset.Id + "_" + i.Id + ".jpeg";
                        _ImageServerID = LVendor_Visit_XMissionStructures_Image.UploadImage(i, _FullPathImage);
                        if (_ImageServerID > 0)
                            LogicLayer.UpdateImageServerID(_ImageServerID, i.Id, m_DatabaseConnectionString);
                        _CountUploaded--;
                        m_UploaderWorker.ReportProgress(ReportProgress(_CountUploaded));
                        System.Threading.Thread.Sleep(ConvertHelper.ToInt32(ConfigurationManager.AppSettings["TimeWaitUpImages"]));
                    }
                }
            }
            catch (Exception ex)
            {
                e.Cancel = true;
                return;
            }
        }

        private DirectoryInfo GetImagesDirectory()
        {
            DirectoryInfo _MobileDatabaseDirectory = new DirectoryInfo(Path.GetDirectoryName(m_DatabaseConnectionString));
            DirectoryInfo[] _Directories = _MobileDatabaseDirectory.GetDirectories();
            return _Directories[0];
        }

        protected override void UploaderWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                if (m_DatabaseConnectionString != null)
                {
                    XMLHelper.UpdateImageNode(Constants.K_XmlOutboxPath, m_CurrentDatabase.Id);
                    CopyDirectories(m_DatabaseConnectionString);
                    m_CurrentDatabase = null;

                    if (!HasNextUpload())
                    {
                        OnUploaderCompleted(sender, new EventArgs());
                    }
                    else
                    {
                        StartUploadQueue();
                    }
                }

            }
            else
            {
                OnUploadCancelled(sender, new EventArgs());
            }
        }

        public override void StopProcess()
        {
            if (m_CurrentDatabase != null)
                m_CurrentDatabase.IsImagesUploaded = false;
            base.StopProcess();
        }

        private void CopyDirectories(string connectionString)
        {
            DirectoryInfo _DirectorySource = null;
            try
            {
                string _DirectoryName = Path.GetDirectoryName(connectionString);
                _DirectorySource = new DirectoryInfo(_DirectoryName);
                DirectoryInfo _DirectoryDestination = new DirectoryInfo(Constants.K_SentPath);
                DirHelper.isDirectory(_DirectoryDestination.FullName + Path.DirectorySeparatorChar + _DirectorySource.Name);
                _DirectoryDestination = new DirectoryInfo(_DirectoryDestination.FullName + Path.DirectorySeparatorChar + _DirectorySource.Name);
                DirHelper.CopyFiles(_DirectorySource, _DirectoryDestination, true);
            }
            catch (IOException ioex)
            {
                ErrorManager.Log("IOException", "UploaderImages.CopyDirectories " + ioex.TargetSite, ioex.Message, ioex.StackTrace);
            }
            catch (System.Security.SecurityException secex)
            {
                ErrorManager.Log("System.Security.SecurityException", "UploaderImages.CopyDirectories " + secex.TargetSite, secex.Message, secex.StackTrace);
            }
            finally
            {
                //Clean directory
                _DirectorySource.Delete(true);
            }
        }

    }
}
